package li.nibble.twittertido.webservice;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import li.nibble.twittertido.Utils;
import li.nibble.twittertido.beans.Comment;
import li.nibble.twittertido.beans.Tweet;
import li.nibble.twittertido.beans.User;
import li.nibble.twittertido.model.DataBase;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public abstract class Client {

	public static final String URL_BASE = "http://nibble.li/twittertido/web/";
	public static final String GET_QUEUE = "getQueueAndroid.php";
	public static final String GET_HOME = "getHomeAndroid.php";
	public static final String GET_COMMENTS = "getComments.php";
	public static final String GET_TOP_USERS = "topUsers.php";
	public static final String GET_TOP_TWEETS = "getTopAndroid.php";
	public static final String GET_RANDOM_TWEETS = "getRandom.php";
	public static final String COMMENT = "comment.php";
	public static final String SEND_TWEET = "insert.php";
	public static final String CREATE_USER = "createUser.php";
	public static final String LOGIN = "login.php";
	public static final String GET_INFO = "getInfo.php";
	public static final String VOTE = "like.php";
	public static final String LIKE = "like.php";

	public static final String GET_INFO_FIELD_EMAIL = "email";
	public static final String GET_INFO_FIELD_EXISTS_USER = "existsUser";
	public static final String GET_INFO_FIELD_EXISTS_USER_EMAIL = "existsUserEmail";

	public static ArrayList<Tweet> getQueue(Context context) {
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE
					+ GET_QUEUE
					+ "?user="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_USERNAME)
					+ "&password="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_PASSWORD));
			// Log.e("Client.sendTweet", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("tweets");
				for (int i = 0; i < searchs.length(); i++) {

					Tweet tweet = new Tweet();
					tweet.setId(searchs.getJSONObject(i).getInt("id"));
					tweet.setTweet(searchs.getJSONObject(i).getString("tweet"));
					tweet.setUser(searchs.getJSONObject(i).getString(
							"user_tweet"));
					tweets.add(tweet);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return tweets;
	}

	public static ArrayList<Tweet> getNewHome(Context context) {
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(String.format(URL_BASE + GET_HOME
					+ "?last=%s", URLEncoder.encode(DataBase.getPreference(
					context, DataBase.PREFERENCES_NAME_LAST_HOME), "UTF8")));
			// Log.e("Client.getHome", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("tweets");
				for (int i = 0; i < searchs.length(); i++) {
					Tweet tweet = new Tweet();
					tweet.setId(searchs.getJSONObject(i).getInt("id"));
					tweet.setTweet(searchs.getJSONObject(i).getString("tweet"));
					tweet.setUser(searchs.getJSONObject(i).getString(
							"user_tweet"));
					tweet.setDate(searchs.getJSONObject(i).getString("date"));
					tweets.add(tweet);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return tweets;
	}

	public static ArrayList<Tweet> getRandom(Context context) {
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE
					+ GET_RANDOM_TWEETS
					+ "?user="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_USERNAME)
					+ "&password="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_PASSWORD));
			// Log.e("Client.getHome", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("tweets");
				for (int i = 0; i < searchs.length(); i++) {
					Tweet tweet = new Tweet();
					tweet.setTweet(searchs.getJSONObject(i).getString("tweet"));
					tweet.setUser(searchs.getJSONObject(i).getString(
							"user_tweet"));
					tweet.setId(searchs.getJSONObject(i).getInt("id"));
					tweet.setLikes(searchs.getJSONObject(i).getInt("likes"));
					tweet.setLikes(searchs.getJSONObject(i).getInt("dislikes"));
					tweets.add(tweet);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return tweets;
	}

	public static ArrayList<Tweet> getTopTweets(Context context) {
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE
					+ GET_TOP_TWEETS
					+ "?user="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_USERNAME)
					+ "&password="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_PASSWORD));
			// Log.e("Client.getTopTweets", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("tweets");
				for (int i = 0; i < searchs.length(); i++) {
					Tweet tweet = new Tweet();
					tweet.setTweet(searchs.getJSONObject(i).getString("tweet"));
					tweet.setUser(searchs.getJSONObject(i).getString(
							"user_tweet"));
					tweet.setId(searchs.getJSONObject(i).getInt("id"));
					tweet.setLikes(searchs.getJSONObject(i).getInt("likes"));
					tweet.setLikes(searchs.getJSONObject(i).getInt("dislikes"));
					tweets.add(tweet);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return tweets;
	}

	public static ArrayList<User> getTopUsers(Context context) {
		ArrayList<User> users = new ArrayList<User>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE
					+ GET_TOP_USERS
					+ "?user="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_USERNAME)
					+ "&password="
					+ DataBase.getPreference(context,
							DataBase.PREFERENCES_NAME_PASSWORD));
			// Log.e("Client.getTopUsers", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("users");
				for (int i = 0; i < searchs.length(); i++) {
					User user = new User();
					user.setUsername(searchs.getJSONObject(i).getString(
							"user_tweet"));
					user.setPublished(searchs.getJSONObject(i).getInt("total"));
					users.add(user);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return users;
	}

	public static ArrayList<Comment> getComments(Context context, int id) {
		ArrayList<Comment> comments = new ArrayList<Comment>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + GET_COMMENTS + "?tweet_id="
					+ id);
			// Log.e("Client.getHome", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("comments");
				for (int i = 0; i < searchs.length(); i++) {
					Comment comment = new Comment();
					comment.setId(searchs.getJSONObject(i).getInt("id"));
					comment.setComment(searchs.getJSONObject(i).getString(
							"comment"));
					comment.setUsername(searchs.getJSONObject(i).getString(
							"username"));
					comments.add(comment);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return comments;
	}

	public static ArrayList<Tweet> getNewQueue(Context context) {
		ArrayList<Tweet> tweets = new ArrayList<Tweet>();
		try {
			JSONObject j;
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(String.format(
					URL_BASE
							+ GET_QUEUE
							+ "?user="
							+ DataBase.getPreference(context,
									DataBase.PREFERENCES_NAME_USERNAME)
							+ "&password="
							+ DataBase.getPreference(context,
									DataBase.PREFERENCES_NAME_PASSWORD)
							+ "&last=%s", URLEncoder.encode(DataBase
							.getPreference(context,
									DataBase.PREFERENCES_NAME_LAST_QUEUE),
							"UTF8")));
			// Log.e("Client.getQueue", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(Utils.convertStreamToString(entity
						.getContent()));
				JSONArray searchs = j.getJSONArray("tweets");
				for (int i = 0; i < searchs.length(); i++) {
					Tweet tweet = new Tweet();
					tweet.setId(searchs.getJSONObject(i).getInt("id"));
					tweet.setTweet(searchs.getJSONObject(i).getString("tweet"));
					tweet.setUser(searchs.getJSONObject(i).getString(
							"user_tweet"));
					tweet.setDate(searchs.getJSONObject(i).getString("date"));
					tweets.add(tweet);
				}
			}
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return tweets;
	}

	public static boolean sendTweet(Context context, Tweet tweet, String url) {
		try {
			HttpClient client = new DefaultHttpClient();

			String date = tweet.getDate();
			String tweet_txt = tweet.getTweet();

//			Log.e("Client.sendTweet", tweet_txt);

			HttpPost httppost = new HttpPost(URL_BASE + SEND_TWEET);

			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs
					.add(new BasicNameValuePair("user", DataBase.getPreference(
							context, DataBase.PREFERENCES_NAME_USER_ID)));
			nameValuePairs.add(new BasicNameValuePair("date_created", date));
			nameValuePairs.add(new BasicNameValuePair("tweet_url", url));
			nameValuePairs.add(new BasicNameValuePair("user_tweet", tweet.getUser()));
			nameValuePairs.add(new BasicNameValuePair("tweet", tweet_txt));
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

//			HttpGet get = new HttpGet(URL_BASE
//					+ SEND_TWEET
//					+ "?user="
//					+ DataBase.getPreference(context,
//							DataBase.PREFERENCES_NAME_USER_ID)
//					+ "&date_created=null&tweet_url=" + url + "&user_tweet="
//					+ tweet.getUser() + "&tweet=" + tweet_txt);
//
//			Log.e("Client.sendTweet", get.getURI().toURL().toString());

			HttpResponse response;
			response = client.execute(httppost);
			response.getEntity();
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return true;
	}

	public static int createUser(String user, String password, String email) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + CREATE_USER + "?user=" + user
					+ "&password=" + email + "&email=" + password);
			// Log.e("Client.sendTweet", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			return Integer.parseInt(in.readLine().trim());
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}

		return 0;
	}

	public static String getEmail(String user, String password) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + GET_INFO + "?field="
					+ GET_INFO_FIELD_EMAIL + "&user=" + user + "&password="
					+ password);
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			String result = in.readLine().trim();
			// Log.e("Client.login", result + "");
			return result;
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return "null";
	}

	public static int login(String user, String password) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + LOGIN + "?user=" + user
					+ "&password=" + password);
			// Log.e("Client.login", URL_BASE + LOGIN + "?user=" + user
			// + "&password=" + password);
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			int result = Integer.parseInt(in.readLine());
			// Log.e("Client.login", result + "");
			return result;
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return -3;
	}

	public static boolean existUser(String user) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + GET_INFO + "?user=" + user
					+ "&field=" + GET_INFO_FIELD_EXISTS_USER);
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			int result = Integer.parseInt(in.readLine());
			// Log.e("Client.login", result + "");
			return result > 0;
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return true;
	}

	public static boolean existUserEmail(String email) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(URL_BASE + GET_INFO + "?email=" + email
					+ "&field=" + GET_INFO_FIELD_EXISTS_USER_EMAIL);
			HttpResponse response;
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			int result = Integer.parseInt(in.readLine());
			// Log.e("Client.login", result + "");
			return result > 0;
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
		return true;
	}

	// public static void vote(Context context, int id_tweet, int like) {
	// try {
	// HttpClient client = new DefaultHttpClient();
	//
	// String user = DataBase.getPreference(context,
	// DataBase.PREFERENCES_NAME_USERNAME);
	// int user_id = Integer.parseInt(DataBase.getPreference(context,
	// DataBase.PREFERENCES_NAME_USER_ID));
	// String password = DataBase.getPreference(context,
	// DataBase.PREFERENCES_NAME_PASSWORD);
	//
	// HttpGet get = new HttpGet(URL_BASE + VOTE + "?user=" + user
	// + "&user_id=" + user_id + "&password=" + password
	// + "&tweet=" + id_tweet + "&like=" + like);
	// HttpResponse response;
	// response = client.execute(get);
	// @SuppressWarnings("unused")
	// HttpEntity entity = response.getEntity();
	// } catch (Exception e) {
	// Log.e(Client.class.getName(), e.getLocalizedMessage());
	// }
	// }

	public static void like(Context context, int id_tweet, int like) {
		try {
			HttpClient client = new DefaultHttpClient();

			HttpGet get = new HttpGet(URL_BASE + LIKE + "?tweet_id=" + id_tweet
					+ "&like=" + like);
//			 Log.e("Like", get.getURI().toURL().toString());
			HttpResponse response;
			response = client.execute(get);
			@SuppressWarnings("unused")
			HttpEntity entity = response.getEntity();
			DataBase.updateLikeTweet(context, id_tweet, like);
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
	}

	public static void comment(Context context, int id_tweet, String username,
			String comment) {
		try {
			HttpClient client = new DefaultHttpClient();

			HttpGet get = new HttpGet(String.format(URL_BASE + COMMENT
					+ "?tweet_id=" + id_tweet + "&user=" + username
					+ "&comment=%s", URLEncoder.encode(comment, "UTF8")));
			HttpResponse response;
			response = client.execute(get);
			@SuppressWarnings("unused")
			HttpEntity entity = response.getEntity();
		} catch (Exception e) {
			Log.e(Client.class.getName(), e.getLocalizedMessage());
		}
	}

}
